package me.luraframework.gateway.module.log;

import lombok.RequiredArgsConstructor;
import me.luraframework.commons.model.PageReqeust;
import me.luraframework.commons.model.PageDto;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

/**
 * @ description: LogController
 * @ author: Liu Ran
 * @ data: 7/11/23 10:47
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("gateway/logs")
public class GatewayLogController {

    private final GatewayLogRepository gatewayLogRepository;
    private final R2dbcEntityTemplate r2dbcEntityTemplate;

    @GetMapping
    public Mono<PageDto<GatewayLog>> list(PageReqeust pageReqeust) {
        PageRequest pageable = PageRequest.of(pageReqeust.getPage() - 1, pageReqeust.getSize(), Sort.by(Sort.Direction.DESC, "requestTime"));
        return Mono.zip(r2dbcEntityTemplate.select(GatewayLog.class).matching(Query.empty().with(pageable)).all().collectList(),
                        r2dbcEntityTemplate.select(GatewayLog.class).count())
                .map(tuple -> PageDto.of(tuple.getT1(), tuple.getT2()));
    }
}
